import React, { useState } from 'react'
import { UserInfoApi, chengeUserInfoApi } from '../../request/api'
import { Button, Checkbox, Form, Input, message, Upload } from 'antd';
import { connect } from "react-redux"
import { Dispatch } from 'redux'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';

interface IPops {
  changeKeyFn: () => void;
}

const beforeUpload = (file: any) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

/* const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}; */

function Means(props: IPops) {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const getUserInfo = () => {
    UserInfoApi().then(res => {
    })
  }
  interface IRes {
    errCode: number;
    message: string;
    data: [];
  }

  const onFinish = (values: any) => {
    if(!values.username){
      message.error('请输入用户名')
      return
    }
    if(!values.password){
      message.error('请输入密码')
      return
    }
    chengeUserInfoApi({
      username: values.username || '',
      password: values.password || ''
    }).then((res: any) => {
      if (res.errCode === 0) {
        let { avatar, username } = res.data[0]
        localStorage.setItem("avatar", avatar)
        localStorage.setItem("username", username)
        localStorage.setItem("cms-token", res.data[0]['token'])
        props.changeKeyFn()
        message.success(res.message)
      } else {
        message.warning(res.message)
      }
    })
  };

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if(info.file.response.errCode == 0){
        message.success("头像修改成功");
        localStorage.setItem("avatar",info.file.response.data.avatar)
        localStorage.setItem("username",info.file.response.data.username)
        localStorage.setItem("cms-token",info.file.response.data['cms-token'])
        // 更新组件
        props.changeKeyFn()
      }
      setLoading(false);
      // Get this url from response in real world.
      /* getBase64(info.file.originFileObj as RcFile, url => {
        console.log(url)
        setLoading(false);
        setImageUrl(url);
      }); */
    }
  };

  const UploadButton = () => (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );



  return (
    <div>
      <Form
        style={{ width: "400px" }}
        name="basic"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="on"
      >
        <Form.Item
          label="Username"
          name="username"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 20, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="http://localhost:9000/manage/upload"
        headers={
          { "cms-token": localStorage.getItem("cms-token") as string }
        }
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : <UploadButton/>}
      </Upload>
    </div>
  );

}

const mapDispachToProps = (dispatch: Dispatch) => {
  return {
    changeKeyFn() {
      dispatch({ type: 'changekey' })
    }
  }
}

export default connect(null, mapDispachToProps)(Means)